
var StrpageHeight = window.innerHeight;  // 获取当前页面的高度
var StrpageWidth = window.innerWidth;  // 获取当前页面的宽度

// console.log('页面高度:', StrpageHeight);
// console.log('页面宽度:', StrpageWidth);

// var portID=7073;  //全局公用端口   公司测试使用端口
// var portID=7073;  //全局公用端口   虹桥 使用端口
// var openID='oSIC35zpBotNrNd2er5FUFcMSbAM';  //全局公用的 登录名对应的 openid
/***************************************************************/
var str1='white';  //公司自用  测试
var localname='东';  //本厂名称  用于喷码枪打印
var RCName="精之研 网筒仓库管理系统";
/********************************************************************/

// var strLin='192.168.0.206:7076/barrelbe/';
var strLin='../../../../showabe/';
var strLinIMG='../../../../tradebe/drawing/';

var Strusersid=localStorage.getItem("usersid");
var Strusername=localStorage.getItem("username");
var StremployeeSid=localStorage.getItem("employeeSid");
var Struserdata=JSON.parse(localStorage.getItem('userdata'));

/********************************************************************/
// pview,pnew,pupdate,pdelete,paudit,pcancel,pprint,pexport,pmoney,
//  查看, 新增, 修改,    删除,  审核,    作废,   打印,   导出,   金额
//判断是否有权限
function determineQX(htmlName,QXName) {
    if (Strusername==='开发者'){return true;}
    let result01 = Struserdata.filter(function(item) {return item.usersid === Strusersid && item.menusid === htmlName});
    if (result01.length>0){
        if (result01[0][QXName]===1){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
    // console.log(result01[0][QXName])
}

/************************************************************************/
//根据打开链接的方式获取不同接口
function getFullUrl(){
    const withProtocol = window.location.href;
    const arr = withProtocol.split(':');
    const protocol = arr[0];

    const hostAndPort = window.location.host;
    const pre = `${protocol}://${hostAndPort}/zipperdye`;
    return `${pre}/`;
}

function getFullUrlprint(){
    const withProtocol = window.location.href;
    const arr = withProtocol.split(':');
    const protocol = arr[0];

    const hostAndPort = window.location.host;
    const pre = `${protocol}://${hostAndPort}`;
    return `${pre}/`;
}

// function getFullUrl(url){
//     const withProtocol = window.location.href
//     const arr = withProtocol.split(':');
//     const protocol = arr[0];
//
//     const hostAndPort = window.location.host;
//     const pre = `${protocol}://${hostAndPort}/zipperdye`;
//     return `${pre}/${url}`;
// }
/*****************************************************/
function formatNowSQL() {
    $.ajax({
        url: strLin + "customSqlAccount/callProc",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getNowDatetime']),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            console.log(data[0]);
            console.log(data[0].NowDatetime);
        }
    });
}


/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}
function getnewdatetime(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return  add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function formatNow() {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function getDaytime(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate + " 22:00:00";
};

/****************************************************/
/***************************************************************************/
function getDay(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate ;
};

//获取本月日期
function getDayNow() {
    var today = new Date();
    var targetday_milliseconds = today.getTime();
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth ;
};

//获取本月日期 一号
function getDayNow01() {
    var today = new Date();
    var targetday_milliseconds = today.getTime();
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-01"  ;
};

//获取上个月日期
function getDayPrevious() {
    var currentDate = new Date(); // 当前日期
    var previousMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);

    var year = previousMonth.getFullYear(); // 上个月的年份
    var month = previousMonth.getMonth() + 1; // 上个月的月份（注意月份从 0 开始，所以需要 +1）
    // var date = previousMonth.getDate(); // 上个月的日期

    return year + "-" + add0(month);
};

function getNowDate(val) {
    var time = new Date();
    var d = time.getDate();

    if (val>d){
        return getDayPrevious()+ '-' + add0(val);
    }else{
        return getDayNow()+ '-' + add0(val);
    }

}

// 根据日期转换成 完成的年月日 如果本日是1/1，把‘12/29’转换成上一年的日期
function formatDate_md(dateStr) {
    let today = new Date();
    let year = today.getFullYear();

    let dateStrNew=isNull(dateStr,'');
    let cleanedStr = dateStrNew.replace(/[^0-9/]/g, '');  // 除字符串中除了数字和 '/' 之外的所有字符，使用正则表达式进行匹配和替换

    let SteDate=year + '/' + cleanedStr;  //火狐浏览器不支持直接转换 日期格式 7/8 要拼接完整的日期格式 2023/7/8
    let date = new Date(SteDate);
    let month = date.getMonth() + 1;
    let day = date.getDate();


    if (month > today.getMonth()+1 || (month == today.getMonth()+1 && day > today.getDate())) {
        year -= 1;
    }

    if (month < 10) month = '0' + month;
    if (day < 10) day = '0' + day;

    return year + '-' + month + '-' + day;
}
// 根据日期转换成 完成的年月日 如果本日是1/1，把‘12/29’转换成上一年的日期
function formatDate_ymd(dateStr) {
    let date = new Date(dateStr);
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let year = date.getFullYear();

    if (month < 10) month = '0' + month;
    if (day < 10) day = '0' + day;

    return year + '-' + month + '-' + day;
}

function doHandleMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
};

/**
 * 判断是否null
 * @param data
 * 为空可自定义 val 值
 */
function isNull(data,val){
    return (data == "" || data == undefined || data == null || data == NaN) ? val : data;
}


//获取浏览器地址参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}
//获取浏览器地址参数（参数为中文）
function getRequest() {
    var url = window.location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            //就是这句的问题
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
            //之前用了unescape()
            //才会出现乱码
        }
    }
    return theRequest;
}


function getUrlParams() {
    var search = window.location.search;
    // 写入数据字典
    var tmparray = search.substr(1, search.length).split("&");
    var paramsArray = new Array;
    if (tmparray != null) {
        for (var i = 0; i < tmparray.length; i++) {
            var reg = /[=|^==]/;  // 用=进行拆分，但不包括==
            var set1 = tmparray[i].replace(reg, '&');
            var tmpStr2 = set1.split('&');
            var array = new Array;
            array[tmpStr2[0]] = tmpStr2[1];
            paramsArray.push(array);
        }
    }
    // 将参数数组进行返回
    return paramsArray;
}

//使用 JavaScript 中的正则表达式和字符串方法来获取中文字符串每个中文的首字母字符串
//以下代码只能处理中文字符，如果字符串中包含其他字符（如英文字母、数字、标点符号等），则会忽略它们
function getChineseInitials(str) {
    let initials = "";
    for (let i = 0; i < str.length; i++) {
        let char = str.charAt(i);
        // 使用 Unicode 编码范围判断是否为中文字符
        if (char >= "\u4e00" && char <= "\u9fa5") {
            // 获取中文字符的 Unicode 编码
            let code = str.charCodeAt(i);
            // 根据编码计算出中文字符的首字母
            let initial = String.fromCharCode((code - 0x4e00 + 0x20) % 0x24 + 0x41);
            initials += initial;
        }
    }
    return initials;
}

//kendoui 根据列名设置列隐藏
//使用方法
// var grid = $("#grid").data("kendoGrid");
// grid.hideColumn("fieldName");
function hideGridColumn(grid, fieldName) {
    var columns = grid.columns;
    for (var i = 0; i < columns.length; i++) {
        var column = columns[i];
        if (column.field === fieldName) {
            column.hidden = true;
            break;
        }
    }
    grid.refresh();
}

/**
 * 数组排序
 * @param arr
 * @param oldIndex
 * @param newIndex
 * @returns {*}
 */
function reorder(arr, oldIndex, newIndex) {
    if (oldIndex == newIndex) return arr;
    if (oldIndex > newIndex) {
        arr.splice(newIndex, 0, arr[oldIndex])
        arr.splice(oldIndex + 1, 1);
    } else {
        arr.splice(newIndex, 0, arr[oldIndex]);
        arr.splice(oldIndex - 1, 1);
    }
    return arr;
}

/**
 * 初始化
 * @param options
 */
function initCombobox(options) {
    let columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}


/**
 * 装载kendoGrid网格
 * @param grid01        dom
 * @param columnsName   列字段名
 * @param columns       定义的列属性数组
 * @param suffix        后缀
 */
function loadOptions(grid01, columnsName, columns, suffix) {
    var columnsNameNew=[];
    var n=0;
    columns.forEach(item => {
        if (item['field']) {
            columnsNameNew.push({'fieldName':item['field'],'columnWidth':item['width'],'hidden':item['hidden'],'seq':n});
            n++;
        }
    });

    // console.log(columnsNameNew);
    var Strcolumns={
        'objectSid':menuId + suffix,
        "styleList": columnsNameNew
    };
    //后端获取记忆列
    $.ajax({
        headers: {"usersid":Strusersid},
        url: strLin + 'customTableStyle/getOrInit',
        traditional: true,
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(Strcolumns),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            var data=cdata.data;
            if (!data) {
                $.messager.alert('提示', '无法加载网格配置,请重新打开页面!', 'warning')
                return;
            }
            // console.log(data);

            for (let x of columns) {
                let col = x['field'];
                // if (suffix) col += suffix;
                let dataNew = data.filter(function(item) {return item.fieldName == col;});
                if (dataNew.length==0) continue;
                let width = dataNew[0].columnWidth;
                let hidden = dataNew[0].hidden;
                x['width'] = width ? parseFloat(width) : 0;
                if (!x['hidden'])
                    x['hidden'] = hidden;
                x['serialNumber'] = dataNew[0].seq;
            }
            columns.sort((x, y) => x.serialNumber - y.serialNumber);
            grid01.setOptions({
                columns: columns
            });
            if (typeof initCombobox == 'function')
                initCombobox(grid01.getOptions())
        },
        error: function () {
            grid01.setOptions({
                columns: columns
            });
        }
    });
}

/**
 * 读取网格列配置
 * @param element   dom元素
 * @param menuId    菜单编号
 */
function getColumnsConfiguration(element, menuId, suffix = '') {
    if ($(element).length <= 0) return;
    let opts = $(element).datagrid('getColumnFields');
    if (opts.length <= 0) return;
    $.ajax({
        url: "deploy/query.do",
        data: {menuId: menuId, name: opts.map(item => item + suffix)},
        dataType: "json",
        type: "post",
        traditional: true,
        success: function (data) {
            if (data) {
                for (let i of opts) {
                    let col = $(element).datagrid('getColumnOption', i);
                    let configItem = data[i + suffix];
                    if (!configItem) continue;
                    if (configItem['width'] != undefined && configItem['width'] != null)
                        col.width = configItem['width'];
                    if (configItem['hidden']) {
                        $(element).datagrid('hideColumn', i);
                    } else {
                        $(element).datagrid('showColumn', i);
                    }
                }
                $(element).datagrid();
            }
        }
    });
}



/**
 * 设置全屏
 */
function fullScreen() {
    var el = document.documentElement;
    var rfs = el.requestFullScreen || el.webkitRequestFullScreen ||
        el.mozRequestFullScreen || el.msRequestFullScreen;
    if (typeof rfs != "undefined" && rfs) {
        rfs.call(el);
    } else if (typeof window.ActiveXObject != "undefined") {
        // for IE，这里其实就是模拟了按下键盘的F11，使浏览器全屏
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript != null) {
            wscript.SendKeys("{F11}");
        }
    }
}

/*
 * 退出全屏
 */
function exitFull() {
    // 判断各种浏览器，找到正确的方法
    var exitMethod = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.webkitExitFullscreen;
    if (exitMethod) {
        exitMethod.call(document);
    }
    else if (typeof window.ActiveXObject !== "undefined") {// for// Internet// Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}


/**
 * @description 数字转中文数码
 *
 * @param {Number|String}   num     数字[正整数]
 * @param {String}          type    文本类型，lower|upper，默认upper
 *
 * @example number2text(100000000) => "壹亿元整"
 */
function number2text  (number, type = "upper") {
    // 配置
    const confs = {
        lower: {
            num: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
            unit: ["", "十", "百", "千", "万"],
            level: ["", "万", "亿"]
        },
        upper: {
            num: ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"],
            unit: ["", "拾", "佰", "仟"],
            level: ["", "万", "亿"]
        },
        decimal: {
            unit: ["分", "角"]
        },
        maxNumber: 999999999999.99
    };

    // 过滤不合法参数
    if (Number(number) > confs.maxNumber) {
        console.error(
            `The maxNumber is ${confs.maxNumber}. ${number} is bigger than it!`
        );
        return false;
    }

    const conf = confs[type];
    const numbers = String(Number(number).toFixed(2)).split(".");
    const integer = numbers[0].split("");
    const decimal = Number(numbers[1]) === 0 ? [] : numbers[1].split("");

    // 四位分级
    const levels = integer.reverse().reduce((pre, item, idx) => {
        let level = pre[0] && pre[0].length < 4 ? pre[0] : [];
        let value =
            item === "0" ? conf.num[item] : conf.num[item] + conf.unit[idx % 4];
        level.unshift(value);

        if (level.length === 1) {
            pre.unshift(level);
        } else {
            pre[0] = level;
        }

        return pre;
    }, []);

    // 整数部分
    const _integer = levels.reduce((pre, item, idx) => {
        let _level = conf.level[levels.length - idx - 1];
        let _item = item.join("").replace(/(零)\1+/g, "$1"); // 连续多个零字的部分设置为单个零字

        // 如果这一级只有一个零字，则去掉这级
        if (_item === "零") {
            _item = "";
            _level = "";

            // 否则如果末尾为零字，则去掉这个零字
        } else if (_item[_item.length - 1] === "零") {
            _item = _item.slice(0, _item.length - 1);
        }

        return pre + _item + _level;
    }, "");

    // 小数部分
    let _decimal = decimal
        .map((item, idx) => {
            const unit = confs.decimal.unit;
            const _unit = item !== "0" ? unit[unit.length - idx - 1] : "";

            return `${conf.num[item]}${_unit}`;
        })
        .join("");

    // 如果是整数，则补个整字
    return `${_integer}元` + (_decimal || "整");
};

// function decimalToChinese(decimal) {
//     var chineseNumber = '';
//     var integerPart = Math.floor(decimal);
//     var decimalPart = Math.round(decimal * 100) % 100;
//     var unitMap = ['', '拾', '佰', '仟'];
//     var numberMap = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
//
//     // 处理整数部分
//     if (integerPart === 0) {
//         chineseNumber += '零';
//     } else {
//         var strIntegerPart = String(integerPart).split('').reverse().join('');
//         for (var i = 0; i < strIntegerPart.length; i++) {
//             var digit = parseInt(strIntegerPart[i]);
//             var unit = unitMap[i % 4];
//             if (digit === 0) {
//                 if (chineseNumber[0] !== numberMap[0]) {
//                     chineseNumber = numberMap[0] + chineseNumber;
//                 }
//             } else {
//                 chineseNumber = numberMap[digit] + unit + chineseNumber;
//             }
//         }
//     }
//
//     // 处理小数部分
//     if (decimalPart > 0) {
//         chineseNumber += '元';
//         var strDecimalPart = String(decimalPart);
//         if (decimalPart < 10) {
//             chineseNumber += numberMap[0] + numberMap[parseInt(strDecimalPart[0])] + '分';
//         } else {
//             chineseNumber += numberMap[parseInt(strDecimalPart[0])] + '角';
//             if (strDecimalPart[1] !== '0') {
//                 chineseNumber += numberMap[parseInt(strDecimalPart[1])] + '分';
//             }
//         }
//     } else {
//         chineseNumber += '元整';
//     }
//
//     return chineseNumber;
// }

function decimalToChinese(decimal) {
    var chineseNumber = '';
    var integerPart = Math.floor(decimal);
    var decimalPart = Math.round(decimal * 100) % 100;
    var unitMap = ['', '拾', '佰', '仟'];
    var numberMap = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];

    // 转换整数部分
    if (integerPart === 0) {
        chineseNumber += '零';
    } else {
        var strIntegerPart = String(integerPart).split('').reverse().join('');
        var groupCount = Math.ceil(strIntegerPart.length / 4);
        for (var i = 0; i < groupCount; i++) {
            var group = strIntegerPart.slice(i * 4, (i + 1) * 4);
            var groupChinese = '';
            for (var j = 0; j < group.length; j++) {
                var digit = parseInt(group[j]);
                var unit = unitMap[j % 4];
                if (digit === 0) {
                    if (groupChinese[0] !== numberMap[0]) {
                        groupChinese = numberMap[0] + groupChinese;
                    }
                } else {
                    groupChinese = numberMap[digit] + unit + groupChinese;
                }
            }
            if (groupChinese !== '') {
                if (i > 0) {
                    groupChinese += ['万', '亿'][i - 1];
                }
                chineseNumber = groupChinese + chineseNumber;
            }
        }
    }

    // 转换小数部分
    if (decimalPart > 0) {
        chineseNumber += '元';
        if (decimalPart < 10) {
            chineseNumber += numberMap[0] + numberMap[parseInt(decimalPart)] + '分';
        } else {
            chineseNumber += numberMap[parseInt(decimalPart / 10)] + '角';
            if (decimalPart % 10 !== 0) {
                chineseNumber += numberMap[decimalPart % 10] + '分';
            }
        }
    } else {
        chineseNumber += '元整';
    }

    return chineseNumber;
}